package blue.base.internal.core.net.aio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

/**
 * @author Jin Zheng
 * @since 2021-06-28
 */
public class AioReadHandler implements CompletionHandler<Integer, AioAttachment> {
    private static Logger logger = LoggerFactory.getLogger(AioReadHandler.class);

	public AioReadHandler() {
	}

    @Override
    public void completed(Integer result, AioAttachment att) {
        ByteBuffer buffer = att.getBuffer();
        if (att.isReadMode()) {
            buffer.flip();
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            String str = new String(bytes);
            String hello = "Receive: " + str;
            logger.info(hello);
            buffer.clear();
            buffer.put(hello.getBytes());
            att.setReadMode(false);
            buffer.flip();
            att.getClient().write(buffer, att, this);
            if (str.equals("byte")) {

                try {
                    att.getClient().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            buffer.clear();
            att.getClient().read(buffer, att, this);
            att.setReadMode(true);
        }
    }

    @Override
    public void failed(Throwable exc, AioAttachment attachment) {
        logger.error("Error, ", exc);
    }
}
